/**
 * Created by qingmai on 2017/2/17.
 */
/**
 * Created by qingmai on 2017/2/17.
 */
const gulp = require('gulp');
const config = require('../config'),
    notify = require('gulp-notify'),
    del = require('del'),
    imagemin = require('gulp-imagemin'),
    spritesmith=require('gulp.spritesmith');
    cache = require('gulp-cache');
gulp.task('images', function(cd) {
    del(config.dest.delimage, {dryRun: true}).then(paths => {
    console.log('以删除', paths.join('\n'));
});
    return gulp.src(config.src.image)
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest(config.dest.image))
        .pipe(notify({ message: '图片压缩完成' }));
});
gulp.task('img',function () {
    gulp.watch(config.src.image,['images'])
})


// gulp多张图片自动合成雪碧图
var pingmu = 7.5,danwei = "vw",widthw,heighth,positionw,positionh,sizew,sizeh;
gulp.task('sprit', function () {
    return gulp.src(config.src.imagespritres)//需要合并的图片地址
        .pipe(spritesmith({
            imgName: config.src.spritresimgname,//保存合并后图片的地址
            cssName: config.src.spritresless,//保存合并后对于css样式的地址
            padding:5,//合并时两个图片的间距
            algorithm: 'binary-tree',//注释1
            cssTemplate: function (data) {
                var arr=[];
                // console.log(data.sprites);
                data.sprites.forEach(function (sprite) {
                    widthw = sprite.width/pingmu + 0.2 + danwei;
                    heighth = sprite.height/pingmu + 0.2 + danwei;
                    positionw = sprite.offset_x/pingmu + 0.2;
                    positionh = sprite.offset_y/pingmu + 0.2;
                    sizew = sprite.total_width/pingmu + danwei;
                    sizeh = sprite.total_height/pingmu +danwei;
                    arr.push(".icon-"+sprite.name+
                    "(){" +
                    "background-image: url('"+sprite.escaped_image.slice(3)+"');"+
                    "background-position: "+positionw+danwei+" "+positionh+danwei+";"+
                    "background-repeat: no-repeat;background-size:"+sizew+" "+sizeh+";"+
                    "width:"+widthw+";"+
                    "height:"+heighth+";"+
                    "}\n");
                });
                return arr.join("");
            }

        }))
        .pipe(gulp.dest(''));
});